#include "dbserver.h"
#include "dbparachute.h"

DBServer *g_dbserver = 0;


DBServer::DBServer()
{
	mx_cli = PTHREAD_MUTEX_INITIALIZER;
}

DBServer::~DBServer()
{
	if ( this == g_dbserver ) {
		g_dbserver = 0;
	}
}

DBServer *DBServer::startServer()
{
	if ( !g_dbserver )
	{
		g_dbserver = new DBServer;
	}

	LOGP1 ( "DBServer: [START]" );
	g_dbserver->ssocket.onAccept = DBServer::onAccept;
	g_dbserver->ssocket.onError = DBServer::onError;
	g_dbserver->ssocket.PortOpen ( SRVR_PORT );
	return g_dbserver;
}


void DBServer::onError ( SPipe *pipe, i32 err_code )
{
	LOGP2 ( "SERVER: Server tcp error [#%d]", err_code );
	LOGP2 ("SERVER: Winsock error [%s]",ErrToStr(WSAGetLastError()).c_str());
}

void DBServer::onAccept ( SPipe *pipe, i32 nothing )
{
	if ( pipe->IsReady() )
	{
		LOGP1 ( "ACCEPT" );
		Pipe *p = new Pipe;
		DBClient *client = new DBClient;
		client->connection = p;
		p->onDataSent = DBClient::onDataSent;
		p->onError = DBClient::onPipeError;
		p->onReadyRead = DBClient::onReadyRead;
		p->user_data = ( i32 ) client;
		pipe->Accept ( *p );
		ENTER_CS ( g_dbserver->mx_cli );
		g_dbserver->clients.push_back ( client );
		LEAVE_CS ( g_dbserver->mx_cli );
	}
}

void DBServer::ProcessQuee()
{
    ENTER_CS (mx_cli);
    vector<DBClient*>::iterator i;
    u32 c = 0;
    for (i = clients.begin(); i != clients.end(); i++)
    {
        if (!(*i)->active)
        {
//            LOGP1("REMOVE_IT_ ERASE !!!");
            (*i)->connection->Close(0);
            i = clients.erase( clients.begin() + c);
            if ( !clients.size())
                break;
        }
        c++;
    }


    LEAVE_CS (mx_cli);
}
